// pages/people/add/add.js
import {
  addVisit,
  updateVisit,
  getVisitDetail,
  uploadVisitFile,
  deleteVisitFile,
  getVisitFileUrl
} from '../../../utils/visit'
import {
  getCurrentTimeToMinute
} from '../../../utils/get_time_to_minute'
var localInputCache = {};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'basic', // 默认显示基本信息
    addMode: true, // 是否为新增模式
    formData: {
      // 基本信息
      id: '', // 探访ID
      startTime: '', // 开始时间
      endTime: '', // 结束时间
      visitType: '入户探访', // 探访方式
      serviceName1: '', // 服务对象姓名1
      serviceName2: '', // 服务对象姓名2
      collaborator: '', // 协同探访人员

      // 服务对象基本情况
      familyStructure: '', // 家庭结构
      healthStatus: '', // 健康状况
      economicStatus: '', // 经济状况

      // 探访目的
      visitPurpose: '', // 探访目的

      // 探访内容
      livingEnvironment: '', // 居住环境
      dietSituation: '', // 饮食情况
      dailyActivities: '', // 日常活动
      physicalInquiry: '', // 身体状况询问
      medicalNeeds: '', // 医疗需求询问
      healthGuidance: '', // 健康指导提供
      psychologicalState: '', // 心理状态观察
      emotionalSupport: '', // 情感陪伴与疏导
      policyExplanation: '', // 政策宣传解答
      informationFeedback: '', // 信息收集反馈

      // 问题与需求发现
      lifeIssues: '', // 生活问题
      healthIssues: '', // 健康问题
      psychologicalIssues: '', // 心理问题
      otherNeeds: '', // 其他需求

      // 解决方案与建议
      lifeSolutions: '', // 生活问题解决方案
      lifeSuggestions: '', // 生活问题建议
      healthSolutions: '', // 健康问题解决方案
      healthSuggestions: '', // 健康问题建议
      psychologicalSolutions: '', // 心理问题解决方案
      psychologicalSuggestions: '', // 心理问题建议
      otherSolutions: '', // 其他需求解决方案
      otherSuggestions: '', // 其他需求建议

      // 服务对象反馈
      serviceFeedback: '', // 服务对象反馈内容
      feedbackTime: '', // 反馈时间

      // 探访人员总结
      visitorSummary: '', // 探访人员总结内容

      // 备注与附件
      notes: '', // 备注
      attachmentFiles: [] // 附件文件
    },

    // 协同人员搜索相关
    collaboratorSearchKeyword: '', // 搜索关键词
    collaboratorSearchResults: [], // 搜索结果
    showCollaboratorResults: false, // 是否显示搜索结果
    mockCollaborators: [{
        id: 1,
        name: '张三',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 2,
        name: '李四',
        department: '医疗保健部',
        phone: '13800138002'
      },
      {
        id: 3,
        name: '王五',
        department: '心理咨询部',
        phone: '13800138003'
      },
      {
        id: 4,
        name: '赵六',
        department: '志愿服务部',
        phone: '13800138004'
      },
      {
        id: 5,
        name: '陈七',
        department: '政策宣传部',
        phone: '13800138005'
      },
      {
        id: 6,
        name: '周八',
        department: '社会工作部',
        phone: '13800138006'
      },
      {
        id: 7,
        name: '吴九',
        department: '医疗保健部',
        phone: '13800138007'
      },
      {
        id: 8,
        name: '郑十',
        department: '心理咨询部',
        phone: '13800138008'
      },
      {
        id: 9,
        name: '张4',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 10,
        name: '张5',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 11,
        name: '张6',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 12,
        name: '张7',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 13,
        name: '张8',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 14,
        name: '张9',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 15,
        name: '张10',
        department: '社会工作部',
        phone: '13800138001'
      },
      {
        id: 16,
        name: '张11',
        department: '社会工作部',
        phone: '13800138001'
      },
    ], // 模拟数据

    // 时间选择器相关数据
    startTimeRanges: [
      // 年
      Array.from({
        length: 10
      }, (_, i) => (new Date().getFullYear() + i - 5).toString()),
      // 月
      Array.from({
        length: 12
      }, (_, i) => (i + 1).toString().padStart(2, '0')),
      // 日
      Array.from({
        length: 31
      }, (_, i) => (i + 1).toString().padStart(2, '0')),
      // 时
      Array.from({
        length: 24
      }, (_, i) => i.toString().padStart(2, '0')),
      // 分
      Array.from({
        length: 60
      }, (_, i) => i.toString().padStart(2, '0'))
    ],
    startTimeArray: [5, 0, 0, 0, 0], // 默认选择当前年份、1月1日 00:00

    endTimeRanges: [
      // 年
      Array.from({
        length: 10
      }, (_, i) => (new Date().getFullYear() + i - 5).toString()),
      // 月
      Array.from({
        length: 12
      }, (_, i) => (i + 1).toString().padStart(2, '0')),
      // 日
      Array.from({
        length: 31
      }, (_, i) => (i + 1).toString().padStart(2, '0')),
      // 时
      Array.from({
        length: 24
      }, (_, i) => i.toString().padStart(2, '0')),
      // 分
      Array.from({
        length: 60
      }, (_, i) => i.toString().padStart(2, '0'))
    ],
    endTimeArray: [5, 0, 0, 0, 0], // 默认选择当前年份、1月1日 00:00


    // 附件相关配置
    maxAttachmentCount: 3, // 最大附件数量

  },

  /**
   * 切换左侧边栏
   */
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });

    // 在切换tab后，重置textarea的高度
    setTimeout(() => {
      this.resetTextareaHeight();
    }, 50);
  },

  /**
   * 重置textarea高度
   */
  resetTextareaHeight: function () {
    // 获取当前页面所有textarea节点
    wx.createSelectorQuery()
      .selectAll('.form-textarea')
      .fields({
        dataset: true,
        size: true,
        node: true
      })
      .exec(res => {
        if (res && res[0] && res[0].length > 0) {
          // 操作textarea节点，让它们重新计算高度
          const textareas = res[0];
          textareas.forEach(item => {
            const field = item.dataset.field;
            const value = this.data.formData[field] || '';
            // 先清空值，再重新设置，触发auto-height重新计算
            const data = {};
            data[`formData.${field}`] = '';
            this.setData(data);

            setTimeout(() => {
              const newData = {};
              newData[`formData.${field}`] = value;
              this.setData(newData);
            }, 50);
          });
        }
      });
  },

  /**
   * 处理输入框变化
   */
  inputChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    // 缓存输入内容
    localInputCache[`formData.${field}`] = value;
    // const newData = {};
    // newData[`formData.${field}`] = value;
    // this.setData(newData);
  },
  inputBlur: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = localInputCache[`formData.${field}`];
    if (value !== undefined) {
      const newData = {};
      newData[`formData.${field}`] = value;
      this.setData(newData);
      // 清除缓存
      localInputCache = {};
    }
  },

  /**
   * 协同人员搜索输入变化
   */
  collaboratorSearchInput: function (e) {
    const keyword = e.detail.value;
    this.setData({
      collaboratorSearchKeyword: keyword
    });

    if (keyword.trim() === '') {
      this.setData({
        collaboratorSearchResults: [],
        showCollaboratorResults: false,
        'formData.collaborator': ''
      });
      return;
    }

    // 模拟搜索
    const results = this.data.mockCollaborators.filter(item =>
      item.name.includes(keyword) ||
      item.department.includes(keyword) ||
      item.phone.includes(keyword)
    );

    this.setData({
      collaboratorSearchResults: results,
      showCollaboratorResults: results.length > 0
    });
  },

  /**
   * 选择协同人员
   */
  selectCollaborator: function (e) {
    const selectedItem = e.currentTarget.dataset.item;
    this.setData({
      'formData.collaborator': selectedItem.name,
      collaboratorSearchKeyword: selectedItem.name,
      collaboratorSearchResults: [],
      showCollaboratorResults: false
    });
  },

  /**
   * 隐藏协同人员搜索结果
   */
  hideCollaboratorResults: function () {
    // 延迟隐藏，确保点击事件能正确触发
    setTimeout(() => {
      this.setData({
        showCollaboratorResults: false
      });
    }, 200);
  },

  /**
   * 处理单选框变化
   */
  radioChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.${field}`] = value;
    this.setData(newData);
  },


  /**
   * 处理日期选择器变化
   */
  dateChange: function (e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    const newData = {};
    newData[`formData.${field}`] = value;
    this.setData(newData);
  },

  /**
   * 处理选择器变化
   */
  pickerChange: function (e) {
    const field = e.currentTarget.dataset.field;
    let value;

    // 处理不同的选择器
    if (field === 'serviceName') {
      value = this.data.serviceNameList[e.detail.value];
    } else if (this.data[`${field}List`]) {
      value = this.data[`${field}List`][e.detail.value];
    } else {
      return;
    }

    const newData = {};
    newData[`formData.${field}`] = value;
    // 设置选中的索引
    newData[`${field}Index`] = e.detail.value;
    this.setData(newData);
  },

  /**
   * 开始时间选择器列变化事件
   */
  startTimeColumnChange: function (e) {
    const column = e.detail.column;
    const value = e.detail.value;
    const startTimeRanges = this.data.startTimeRanges;
    const startTimeArray = this.data.startTimeArray;

    // 更新当前列的选择索引
    startTimeArray[column] = value;

    // 根据年月更新日期的范围
    if (column === 0 || column === 1) {
      const year = parseInt(startTimeRanges[0][startTimeArray[0]]);
      const month = parseInt(startTimeRanges[1][startTimeArray[1]]);
      const daysInMonth = new Date(year, month, 0).getDate();

      // 更新日期范围
      startTimeRanges[2] = Array.from({
        length: daysInMonth
      }, (_, i) => (i + 1).toString().padStart(2, '0'));

      // 确保日期不超过当月天数
      if (startTimeArray[2] >= daysInMonth) {
        startTimeArray[2] = daysInMonth - 1;
      }
    }

    this.setData({
      startTimeRanges: startTimeRanges,
      startTimeArray: startTimeArray
    });
  },

  /**
   * 开始时间选择器确认事件
   */
  startTimeChange: function (e) {
    const values = e.detail.value;
    const startTimeRanges = this.data.startTimeRanges;

    // 获取选中的年月日时分
    const year = startTimeRanges[0][values[0]];
    const month = startTimeRanges[1][values[1]];
    const day = startTimeRanges[2][values[2]];
    const hour = startTimeRanges[3][values[3]];
    const minute = startTimeRanges[4][values[4]];

    // 格式化为 yyyy-MM-dd HH:mm 格式
    const startTime = `${year}-${month}-${day} ${hour}:${minute}`;

    this.setData({
      'formData.startTime': startTime,
      startTimeArray: values
    });
  },

  /**
   * 结束时间选择器列变化事件
   */
  endTimeColumnChange: function (e) {
    const column = e.detail.column;
    const value = e.detail.value;
    const endTimeRanges = this.data.endTimeRanges;
    const endTimeArray = this.data.endTimeArray;

    // 更新当前列的选择索引
    endTimeArray[column] = value;

    // 根据年月更新日期的范围
    if (column === 0 || column === 1) {
      const year = parseInt(endTimeRanges[0][endTimeArray[0]]);
      const month = parseInt(endTimeRanges[1][endTimeArray[1]]);
      const daysInMonth = new Date(year, month, 0).getDate();

      // 更新日期范围
      endTimeRanges[2] = Array.from({
        length: daysInMonth
      }, (_, i) => (i + 1).toString().padStart(2, '0'));

      // 确保日期不超过当月天数
      if (endTimeArray[2] >= daysInMonth) {
        endTimeArray[2] = daysInMonth - 1;
      }
    }

    this.setData({
      endTimeRanges: endTimeRanges,
      endTimeArray: endTimeArray
    });
  },

  /**
   * 结束时间选择器确认事件
   */
  endTimeChange: function (e) {
    const values = e.detail.value;
    const endTimeRanges = this.data.endTimeRanges;

    // 获取选中的年月日时分
    const year = endTimeRanges[0][values[0]];
    const month = endTimeRanges[1][values[1]];
    const day = endTimeRanges[2][values[2]];
    const hour = endTimeRanges[3][values[3]];
    const minute = endTimeRanges[4][values[4]];

    // 格式化为 yyyy-MM-dd HH:mm 格式
    const endTime = `${year}-${month}-${day} ${hour}:${minute}`;

    this.setData({
      'formData.endTime': endTime,
      endTimeArray: values
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.visitId) {
      console.log('修改探访')
      this.setData({
        'formData.id': options.visitId,
        addMode: false
      })
    } else {
      console.log('新增探访')
      this.setData({
        'formData.id': options.id,
        addMode: true
      })
    }

    // 初始化时间选择器默认值为当前时间
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentYearIndex = this.data.startTimeRanges[0].findIndex(y => parseInt(y) === currentYear);

    if (currentYearIndex !== -1) {
      let startTimeArray = this.data.startTimeArray.slice();
      let endTimeArray = this.data.endTimeArray.slice();
      startTimeArray[0] = currentYearIndex;
      endTimeArray[0] = currentYearIndex;

      this.setData({
        startTimeArray: startTimeArray,
        endTimeArray: endTimeArray
      });
    }

    // 在页面加载完成后，确保textarea高度正确
    setTimeout(() => {
      this.resetTextareaHeight();
    }, 300);

    // 如果是编辑模式，从服务器获取探访信息
    if (!this.data.addMode) {
      // 加载数据
      wx.showLoading({
        title: '加载中...',
      });

      getVisitDetail(options.visitId).then(res => {
        console.log('获取到的探访详情:', res);
        const data = res.data
        wx.hideLoading();

        if (data) {
          this.setData({
            'formData.startTime': data.beginTime,
            'formData.endTime': data.endTime,
            'formData.visitType': data.method,
            'formData.serviceName1': data.serviceName1,
            'formData.serviceName2': data.serviceName2,
            'formData.collaborator': data.collaborator || '',
            'collaboratorSearchKeyword': data.collaborator || '',
            'formData.familyStructure': data.serviceTarget.familyStructure,
            'formData.healthStatus': data.serviceTarget.healthInformation,
            'formData.economicStatus': data.serviceTarget.economy,
            'formData.visitPurpose': data.visitContent.purpose,
            'formData.livingEnvironment': data.visitContent.environment,
            'formData.dietSituation': data.visitContent.diet,
            'formData.dailyActivities': data.visitContent.dailyActivity,
            'formData.physicalInquiry': data.visitContent.physicalCondition,
            'formData.medicalNeeds': data.visitContent.medicalCommand,
            'formData.healthGuidance': data.visitContent.healthGuidance,
            'formData.psychologicalState': data.visitContent.psychologicalState,
            'formData.emotionalSupport': data.visitContent.emotionalGuidance,
            'formData.policyExplanation': data.visitContent.policyPromotion,
            'formData.informationFeedback': data.visitContent.informationFeedback,
            'formData.lifeIssues': data.solution.lifeIssue,
            'formData.healthIssues': data.solution.healthIssue,
            'formData.psychologicalIssues': data.solution.psychologicalIssue,
            'formData.otherNeeds': data.solution.otherNeeds,
            'formData.lifeSolutions': data.solution.lifeProblemSolution,
            'formData.lifeSuggestions': data.solution.lifeProblemSuggestion,
            'formData.healthSolutions': data.solution.healthProblemSolution,
            'formData.healthSuggestions': data.solution.healthProblemSuggestion,
            'formData.psychologicalSolutions': data.solution.psychologicalProblemSolution,
            'formData.psychologicalSuggestions': data.solution.psychologicalProblemSuggestion,
            'formData.otherSolutions': data.solution.otherNeedsSolution,
            'formData.otherSuggestions': data.solution.otherNeedsSuggestion,
            'formData.serviceFeedback': data.serviceTarget.feedback,
            'formData.feedbackTime': data.serviceTarget.feedbackTime,
            'formData.visitorSummary': data.visitContent.visitorSummary,
            'formData.notes': data.visitContent.remarks,
            'formData.attachmentFiles': data.listyVisitFiles,
          });

          // 初始化时间选择器
          if (data.beginTime && data.endTime) {
            this.initTimePicker(data.beginTime, data.endTime);
          }
        }
      }).catch(err => {
        wx.hideLoading();
        console.error('获取探访详情失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none',
          duration: 2000
        });
      });
    }
  },


  /**
   * 初始化时间选择器
   */
  initTimePicker: function (startTime, endTime) {
    if (startTime) {
      this.initSingleTimePicker(startTime, 'startTimeArray', 'startTimeRanges');
    }

    if (endTime) {
      this.initSingleTimePicker(endTime, 'endTimeArray', 'endTimeRanges');
    }
  },

  /**
   * 初始化单个时间选择器
   */
  initSingleTimePicker: function (timeString, arrayKey, rangesKey) {
    // 解析时间字符串 格式: yyyy-MM-dd HH:mm
    const match = timeString.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/);
    if (!match) return;

    const year = match[1];
    const month = match[2];
    const day = match[3];
    const hour = match[4];
    const minute = match[5];

    // 获取范围数据
    const ranges = this.data[rangesKey];

    // 查找索引
    const yearIndex = ranges[0].findIndex(y => y === year);
    const monthIndex = ranges[1].findIndex(m => m === month);

    // 更新日期范围
    const daysInMonth = new Date(parseInt(year), parseInt(month), 0).getDate();
    const dayRange = Array.from({
      length: daysInMonth
    }, (_, i) => (i + 1).toString().padStart(2, '0'));
    ranges[2] = dayRange;

    const dayIndex = dayRange.findIndex(d => d === day);
    const hourIndex = ranges[3].findIndex(h => h === hour);
    const minuteIndex = ranges[4].findIndex(m => m === minute);

    // 更新数据
    const array = [
      yearIndex !== -1 ? yearIndex : 0,
      monthIndex !== -1 ? monthIndex : 0,
      dayIndex !== -1 ? dayIndex : 0,
      hourIndex !== -1 ? hourIndex : 0,
      minuteIndex !== -1 ? minuteIndex : 0
    ];

    const data = {};
    data[rangesKey] = ranges;
    data[arrayKey] = array;

    this.setData(data);
  },

  /**
   * 提交表单验证
   */
  submitForm: function () {
    const formData = this.data.formData;

    // 表单验证
    if (!formData.startTime) {
      wx.showToast({
        title: '请输入开始时间',
        icon: 'none'
      });
      this.setData({
        activeTab: 'basic'
      });
      return;
    }

    // if (!formData.endTime) {
    //   wx.showToast({
    //     title: '请输入结束时间',
    //     icon: 'none'
    //   });
    //   this.setData({ activeTab: 'basic' });
    //   return;
    // }

    if (!formData.serviceName1) {
      wx.showToast({
        title: '请输入探访人员1',
        icon: 'none'
      });
      return;
    }
    const endTime = getCurrentTimeToMinute();
    //添加探访
    if (this.data.addMode) {
      wx.showLoading({
        title: '提交中...',
      });
      const data = {
        "BeginTime": formData.startTime,
        "EndTime": endTime,
        "Method": formData.visitType,
        'FamilyUid': formData.id,
        "ServiceName1": formData.serviceName1,
        "ServiceName2": formData.serviceName2,
        "Collaborator": formData.collaborator,
        "FamilyStructure": formData.familyStructure,
        "HealthInformation": formData.healthStatus,
        "Economy": formData.economicStatus,
        "Purpose": formData.visitPurpose,
        "Environment": formData.livingEnvironment,
        "Diet": formData.dietSituation,
        "DailyActivity": formData.dailyActivities,
        "PhysicalCondition": formData.physicalInquiry,
        "MedicalCommand": formData.medicalNeeds,
        "HealthGuidance": formData.healthGuidance,
        "PsychologicalState": formData.psychologicalState,
        "EmotionalGuidance": formData.emotionalSupport,
        "PolicyPromotion": formData.policyExplanation,
        "InformationFeedback": formData.informationFeedback,
        "LifeIssue": formData.lifeIssues,
        "HealthIssue": formData.healthIssues,
        "PsychologicalIssue": formData.psychologicalIssues,
        "OtherNeeds": formData.otherNeeds,
        "LifeProblemSolution": formData.lifeSolutions,
        "LifeProblemSuggestion": formData.lifeSuggestions,
        "HealthProblemSolution": formData.healthSolutions,
        "HealthProblemSuggestion": formData.healthSuggestions,
        "PsychologicalProblemSolution": formData.psychologicalSolutions,
        "PsychologicalProblemSuggestion": formData.psychologicalSuggestions,
        "OtherNeedsSolution": formData.otherSolutions,
        "OtherNeedsSuggestion": formData.otherSuggestions,
        "Feedback": formData.serviceFeedback,
        "FeedbackTime": formData.feedbackTime,
        "VisitorSummary": formData.visitorSummary,
        "Remarks": formData.notes,
      }
      // console.log(data)
      // console.log(formData.attachmentFiles)
      setTimeout(() => {
        wx.hideLoading();
        addVisit(data).then(res => {
          // console.log(res)
          if (res.code === 200) {
            if (formData.attachmentFiles.length > 0) {
              const uid = res.uid
              for (let i = 0; i < formData.attachmentFiles.length; i++) {
                const file_name = formData.attachmentFiles[i].name;
                const file_path = formData.attachmentFiles[i].path;
                const data = {
                  'FileName': file_name,
                  'VisitUid': uid,
                  'File': file_path
                }
                uploadVisitFile(data).then(res => {
                  console.log('上传附件返回结果', res)
                })
              }
            }
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                // 当提示框成功显示完成后，会执行这个回调函数
                setTimeout(() => {
                  // 跳转到人员列表
                  wx.navigateBack()
                }, 1000); // 等待提示框显示的时间
              }
            });
          } else {
            wx.showToast({
              title: '提交失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
      }, 1000);
      //修改探访
    } else {
      wx.showLoading({
        title: '提交中...',
      });
      const data = {
        "Uid": formData.id,
        "BeginTime": formData.startTime,
        "EndTime": endTime,
        "Method": formData.visitType,
        "ServiceName1": formData.serviceName1,
        "ServiceName2": formData.serviceName2,
        "Collaborator": formData.collaborator,
        "FamilyStructure": formData.familyStructure,
        "HealthInformation": formData.healthStatus,
        "Economy": formData.economicStatus,
        "Purpose": formData.visitPurpose,
        "Environment": formData.livingEnvironment,
        "Diet": formData.dietSituation,
        "DailyActivity": formData.dailyActivities,
        "PhysicalCondition": formData.physicalInquiry,
        "MedicalCommand": formData.medicalNeeds,
        "HealthGuidance": formData.healthGuidance,
        "PsychologicalState": formData.psychologicalState,
        "EmotionalGuidance": formData.emotionalSupport,
        "PolicyPromotion": formData.policyExplanation,
        "InformationFeedback": formData.informationFeedback,
        "LifeIssue": formData.lifeIssues,
        "HealthIssue": formData.healthIssues,
        "PsychologicalIssue": formData.psychologicalIssues,
        "OtherNeeds": formData.otherNeeds,
        "LifeProblemSolution": formData.lifeSolutions,
        "LifeProblemSuggestion": formData.lifeSuggestions,
        "HealthProblemSolution": formData.healthSolutions,
        "HealthProblemSuggestion": formData.healthSuggestions,
        "PsychologicalProblemSolution": formData.psychologicalSolutions,
        "PsychologicalProblemSuggestion": formData.psychologicalSuggestions,
        "OtherNeedsSolution": formData.otherSolutions,
        "OtherNeedsSuggestion": formData.otherSuggestions,
        "Feedback": formData.serviceFeedback,
        "FeedbackTime": formData.feedbackTime,
        "VisitorSummary": formData.visitorSummary,
        "Remarks": formData.notes,
      }
      // console.log(data)
      // console.log(formData.attachmentFiles)
      setTimeout(() => {
        wx.hideLoading();
        updateVisit(data).then(res => {
          // console.log(res)
          if (res.code === 200) {
            // console.log('formData.attachmentFiles', formData.attachmentFiles)
            //过滤新添加的文件
            const files = formData.attachmentFiles.filter(item => item.name)
            // console.log('files', files)
            if (files.length > 0) {
              const uid = formData.id
              for (let i = 0; i < files.length; i++) {
                const file_name = files[i].name;
                const file_path = files[i].path;
                const data = {
                  'FileName': file_name,
                  'VisitUid': uid,
                  'File': file_path
                }
                uploadVisitFile(data).then(res => {
                  console.log('上传附件返回结果', res)
                })
              }
            }
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                // 当提示框成功显示完成后，会执行这个回调函数
                setTimeout(() => {
                  // 跳转到人员列表
                  wx.navigateBack()
                }, 1000); // 等待提示框显示的时间
              }
            });
          } else {
            wx.showToast({
              title: '提交失败',
              icon: 'none',
              duration: 2000,
            });
          }
        })
      }, 1000);
    }
  },

  /**
   * 上传附件
   */
  uploadFile: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const attachmentFiles = this.data.formData.attachmentFiles || [];

    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video', 'file'],
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: (res) => {
        console.log('选择的媒体文件：', res.tempFiles);

        const file = res.tempFiles[0];
        const fileName = file.tempFilePath.split('/').pop();

        // 更新附件列表
        if (index >= attachmentFiles.length) {
          attachmentFiles.push({
            name: fileName,
            path: file.tempFilePath,
            size: file.size,
            type: this.getFileType(fileName)
          });
        } else {
          attachmentFiles[index] = {
            name: fileName,
            path: file.tempFilePath,
            size: file.size,
            type: this.getFileType(fileName)
          };
        }

        this.setData({
          ['formData.attachmentFiles']: attachmentFiles
        });

        wx.showToast({
          title: '上传成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择文件失败：', err);
        wx.showToast({
          title: '选择文件失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 添加新附件
   */
  addAttachment: function () {
    const attachmentFiles = this.data.formData.attachmentFiles || [];

    // 检查是否已达到最大附件数量
    if (attachmentFiles.length >= this.data.maxAttachmentCount) {
      wx.showToast({
        title: `最多只能添加${this.data.maxAttachmentCount}个附件`,
        icon: 'none'
      });
      return;
    }

    // 调用上传方法，传入当前附件数组长度作为索引
    this.uploadFile({
      currentTarget: {
        dataset: {
          index: attachmentFiles.length
        }
      }
    });
  },

  /**
   * 预览附件
   */
  previewFile: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const attachmentFiles = this.data.formData.attachmentFiles || [];
    const fileKey = e.currentTarget.dataset.filekey;
    if (fileKey) {
      // 显示加载提示
      wx.showLoading({
        title: '文件下载中...',
        mask: true
      });

      const data = {
        'photokey': fileKey
      }
      getVisitFileUrl(data).then(res => {
        // console.log(res);
        if (!res.url) {
          wx.hideLoading();
          wx.showToast({
            title: '获取下载链接失败',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        // 从URL中获取文件名
        const fileName = res.url.split('/').pop().split('?')[0];

        wx.downloadFile({
          url: res.url,
          success: (res) => {
            // console.log(res);
            wx.hideLoading();

            if (res.statusCode === 200) {
              // 根据文件扩展名判断文件类型
              const fileType = this.getFileType(fileName);

              if (fileType === 'image') {
                // 如果是图片，使用previewImage打开
                wx.previewImage({
                  urls: [res.tempFilePath],
                  current: res.tempFilePath,
                  success: function () {
                    console.log('预览图片成功');
                  },
                  fail: function (err) {
                    console.error('预览图片失败', err);
                    wx.showToast({
                      title: '预览图片失败',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                });
              } else if (fileType === 'video') {
                // 如果是视频，打开视频播放
                wx.openVideoEditor({
                  filePath: res.tempFilePath,
                  mode: 'preview',
                  success: function () {
                    console.log('预览视频成功');
                  },
                  fail: function () {
                    // 如果不支持视频编辑器预览，尝试保存到本地
                    const fileManager = wx.getFileSystemManager();
                    fileManager.saveFile({
                      tempFilePath: res.tempFilePath,
                      success: (saveRes) => {
                        console.log(saveRes, '视频已保存到本地');
                        wx.showToast({
                          title: '视频已保存，请手动打开',
                          icon: 'none',
                          duration: 2000
                        });
                      }
                    });
                  }
                });
              } else {
                // 其他类型文件，使用openDocument
                wx.openDocument({
                  filePath: res.tempFilePath,
                  showMenu: true,
                  success: function () {
                    console.log('打开文档成功');
                  },
                  fail: function (err) {
                    console.error('打开文档失败', err);
                    wx.showToast({
                      title: '无法预览此类型文件',
                      icon: 'none',
                      duration: 2000
                    });

                    // 如果无法直接预览，尝试保存到本地
                    const fileManager = wx.getFileSystemManager();
                    fileManager.saveFile({
                      tempFilePath: res.tempFilePath,
                      success: (saveRes) => {
                        console.log(saveRes, '文件已保存到本地');
                        wx.showToast({
                          title: '文件已保存，请手动打开',
                          icon: 'none',
                          duration: 2000
                        });
                      },
                      fail: (err) => {
                        console.error('保存文件失败', err);
                      }
                    });
                  }
                });
              }
            } else {
              wx.showToast({
                title: '下载失败',
                icon: 'none',
                duration: 2000
              });
            }
          },
          fail: (err) => {
            console.log(err);
            wx.hideLoading();
            wx.showToast({
              title: '下载失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
      }).catch(err => {
        console.error('获取文件URL失败', err);
        wx.hideLoading();
        wx.showToast({
          title: '获取文件失败',
          icon: 'none',
          duration: 2000
        });
      });
    } else {
      if (!attachmentFiles[index]) return;

      const file = attachmentFiles[index];

      if (file.type === 'image') {
        wx.previewImage({
          current: file.path,
          urls: [file.path]
        });
      } else if (file.type === 'video') {
        wx.openVideoEditor({
          filePath: file.path,
          mode: 'preview'
        });
      } else {
        wx.openDocument({
          filePath: file.path,
          showMenu: true,
          success: () => {
            console.log('打开文档成功');
          },
          fail: (err) => {
            console.error('打开文档失败：', err);
            wx.showToast({
              title: '无法预览此类型文件',
              icon: 'none'
            });
          }
        });
      }
    }
  },

  /**
   * 获取文件类型
   */
  getFileType: function (fileName) {
    const ext = fileName.split('.').pop().toLowerCase();

    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    const videoExts = ['mp4', 'mov', 'avi', 'wmv', 'flv', 'mkv'];
    const documentExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'txt'];

    if (imageExts.includes(ext)) {
      return 'image';
    } else if (videoExts.includes(ext)) {
      return 'video';
    } else if (documentExts.includes(ext)) {
      return 'document';
    } else {
      return 'other';
    }
  },
  /**
   * 删除附件
   */
  deleteFile: function (e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const uid = e.currentTarget.dataset.uid;
    const attachmentFiles = this.data.formData.attachmentFiles || [];
    if (uid) {
      wx.showModal({
        title: '提示',
        content: '确定要删除该附件吗？',
        success: (res) => {
          if (res.confirm) {
            const data = {
              'fileUid': uid
            }
            deleteVisitFile(data).then(res => {
              // console.log(res)
            })
          }
        }
      })
    }

    // 直接从数组中移除指定索引的附件
    attachmentFiles.splice(index, 1);

    this.setData({
      ['formData.attachmentFiles']: attachmentFiles
    });

    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示时，确保textarea高度正确
    setTimeout(() => {
      this.resetTextareaHeight();
    }, 300);
  },
})